package com.zyj

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

/**
 * @author : zhaoyanjun
 * @time : 2022/3/15
 * @desc : 长文本绘制
 */
class LongText(context: Context, attrs: AttributeSet?) : View(context, attrs) {

    private val paint = Paint()
    private val fontMetrics = Paint.FontMetrics()
    private var textPositionY = 0f //Y轴坐标

    private var text =
        "上次安妮随口一句“要不然怎么留得住你”让他想起很多事情：比如他一个国内顶尖农业大学园艺专业的优秀毕业生为什么会来到跟农业一点边都不沾的万筑？又比如他是如何从众多优秀求职者中脱颖而出，成为贺见山的助理？甚至还有公司所有部门最关心的，林助理到底是怎么能在贺总手底下干八年的？安妮点点头附和：“那倒确实，企业文化不错。”说到这里，她又感叹道：“说起来，当初我们一起进的万筑，现在我孩子都两岁了，你怎么还不恋爱？你到底喜欢什么样的啊？”"

    init {
        paint.isAntiAlias = true //抗锯齿
        paint.textAlign = Paint.Align.LEFT
        paint.textSize = 50f
        paint.color = Color.BLACK
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        paint.getFontMetrics(fontMetrics)
        textPositionY = -fontMetrics.top
        while (text.isNotEmpty()) {
            text =
                drawText(canvas, text, width.toFloat(), paint, 0f, textPositionY)
            textPositionY += paint.fontSpacing
        }
    }

    /**
     * 绘制文本
     */
    private fun drawText(
        canvas: Canvas,
        message: String,
        maxWidth: Float,
        paint: Paint,
        x: Float,
        y: Float
    ): String {
        //measureForwards 向前绘制；maxWidth 绘制最大宽度
        val count = paint.breakText(message, 0, message.length, true, maxWidth, floatArrayOf())
        canvas.drawText(message, 0, count, x, y, paint)
        return message.substring(count, message.length)
    }
}